import { Message } from 'element-ui'
import tool from './tool.js'
/**
 * 端同步处理本地进度
 * @param {Object} storage 本地存储对象
 * @param {Number} exam_id 试卷id
 * @param {Boolean} clear 是否清除进度
 * ***/
export function addNewRef(storage, exam_id, clear = false) {
  if (!storage || !exam_id) return
  let obj = storage.get(`questionProgress_${exam_id}`) || '{}'
  try {
    obj = JSON.parse(obj)
  } catch (e) {
    obj = {}
  }

  let { new_ref } = obj
  obj.new_ref = new_ref ? ++new_ref : 1

  if (clear) {
    Object.assign(obj, {
      lastIndex: 0,
      progressStr: '[]',
      ref: 2
    })
  }
  storage.set(`questionProgress_${exam_id}`, JSON.stringify(obj))
}

// 复制
export function copy() {
  var selection = window.getSelection().toString()
  if (!selection) return
  try {
    document.execCommand('copy', false, null)
    Message({
      type: 'success',
      message: '复制成功'
    })
  } catch (err) {
    Message.warning('该浏览器不支持点击复制到剪贴板')
  }
}
// 剪贴,不能使用execCommand实现
export function cut(that) {
  let selection = window.getSelection().toString()
  if (!selection) return
  try {
    document.execCommand('cut', false, null)
    // 写入剪贴板
    navigator.clipboard && navigator.clipboard.writeText(selection)
    // 更新答案
    that.answer = that.answer.replace(selection, '')

    console.log('that.answer--------',that.answer);
    Message({
      type: 'success',
      message: '剪切成功'
    })
  } catch (err) {
    Message.warning('该浏览器不支持点击剪切到剪贴板')
  }
}

function getSelectedText(obj) {
  console.log('obj',obj);
  var userSelection
  if (typeof obj.selectionStart === "number" && typeof obj.selectionEnd === "number") {
    // 非IE浏览器
    // 获取选区的开始位置
    var startPos = obj.selectionStart,
      // 获取选区的结束位置
      endPos = obj.selectionEnd
    console.log("非IE：")
    console.log("选区开始点：" + startPos + "，选区结束点：" + endPos)
    userSelection = obj.value.substring(startPos, endPos)
  } else if (document.selection) {
    // IE浏览器
    console.log("IE：")
    userSelection = document.selection.createRange().text
  }
  
  return userSelection
}
// 粘贴
export function paste(that) {
  let range = that.range
  if (!navigator.clipboard) {
    Message.warning('该浏览器不支持点击粘贴到剪贴板')
    return
  }
  // 获取输入框元素
  let { answerArea } = that.$refs
  try {
    // 获取光标位置
    // let selection = window.getSelection()
    // 获取剪贴板内容
    navigator.clipboard.readText().then(clipText => {
      // 获取光标位置
      // let range = selection.getRangeAt(0)
      // 创建文本节点
      // let textNode = document.createTextNode(clipText)
      // // 插入文本节点
      // range.insertNode(textNode)
      // // 设置光标位置
      // // range.setStartAfter(textNode)
      // // range.setEndAfter(textNode)
      // // 清空剪贴板
      // navigator.clipboard.writeText('')
      // // 更新答案
      // that.answer = answerArea.innerHTML

      that.answer += clipText || ''
      // console.log(this.answer, '3333333')
      // that.$refs.answerArea.innerHTML = that.answer
    })
  } catch (err) {
    Message.warning('该浏览器不支持点击粘贴到剪贴板')
  }
}

// 获取本地的缓存试题信息
export function getLocalExamInfo(exam_id) {
  let questionExamJson = storage.get('question_' + exam_id)
  if (questionExamJson) {
    let result = {}
    try {
      result = JSON.parse(questionExamJson)
    } catch (err) {
      result = {}
    }
    if (!(tool.isObject(result) && tool.isArrayLength(result.questionsList) && tool.isArrayLength(result.parts))) {
      result = {}
    }
    return result
  }
  return {}
}

// 处理答案
export function handlerAnswer(answer) {
  // 清除答案的base64编码
  answer = answer.replace(/<img src="data:image\/png;base64,.*?">/g, '')
  return answer
}
